//
//  XDStatusPictureView.swift
//  weibo
//
//  Created by lucy on 2016/10/28.
//  Copyright © 2016年 com.huashengHuaSheng. All rights reserved.
//

import UIKit
import SDWebImage

    //cell可重用表示
    private let pictureViewCellIdentifier = "pictureViewCellIdentifier"
    //cell间距
    private let cellMargin: CGFloat = 5
    //宽高
    private let cellWH = CGFloat(Int(( XDSCREENW - 20 - cellMargin*2)/3))

    class XDStatusPictureView: UICollectionView{
        var picUrls:[XDPictureInfoModel]?{
        
            didSet{
                // 赋值
                countLabel.text = "\(picUrls?.count ?? 0)"
                dealScaleSize(count: picUrls?.count ?? 0)
                print("picUrls?.count",picUrls?.count)
                // 刷新 UI
                reloadData()
            }

        }
        
        //计算配图size
        func dealScaleSize(count: Int){
        
            //如果是单张图片
            if count == 1 {
                
                //获取key
                let key = picUrls?.first?.thumbnail_pic ?? ""
                // 获取 image 从缓存中获取 image
                let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: key)
                // 因为SDWebImage 下载图片可能因为外界影响导致图图片下载不成功 所以说 防止 image == nil  我们需要做判断
                if image != nil {
                    
                    let result = image!.size
                    self.snp_updateConstraints(closure: { (make) in
                        make.size.equalTo(result)
                    })
                    layoutIfNeeded()
                    let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
                    layout.itemSize = result
                    return
                }
            }
            
            //行数和列数
            let col = count>=3 ? 3 : count
            let row = (count-1)/3+1
            
            //最终宽和高
            let w = CGFloat(col) * cellWH + CGFloat(col - 1) * cellMargin
            let h = CGFloat(row) * cellWH + CGFloat(row - 1)*cellMargin
            
            // 更新约束
            self.snp_updateConstraints(closure: { (make) in
                make.size.equalTo(CGSize(width: w, height: h))
            })
            
            layoutIfNeeded()
            // 设置 itemSize
            let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
            layout.itemSize = CGSize(width: cellWH, height: cellWH)
            layout.minimumLineSpacing = cellMargin
            layout.minimumInteritemSpacing = cellMargin

        }
        
        override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
            super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
            setupUI()
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        private func setupUI(){
            // 设置代理
            dataSource = self
            // 注册 cell
            register(XDStatusPictureViewCell.self, forCellWithReuseIdentifier: pictureViewCellIdentifier)
            // 添加控件
            addSubview(countLabel)
            // 添加约束
            countLabel.snp_makeConstraints { (make) in
                make.center.equalTo(self)
            }

        }
        
        // MARK: - 懒加载控件
        private lazy var countLabel: UILabel = {
            let lab = UILabel(textColor: UIColor.red, textSize: 35, textContent: "")
            lab.textAlignment = .center
            return lab
        }()
}

//MARK: - UICollectionViewDataSource
extension XDStatusPictureView: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: pictureViewCellIdentifier, for: indexPath) as! XDStatusPictureViewCell
        // 赋值
        cell.picUrl = picUrls![indexPath.item]
        return cell
    }
}

// 自定义 配图cell
class XDStatusPictureViewCell: UICollectionViewCell {
    
    // 定义数据供外界调用
    var picUrl: XDPictureInfoModel?{
        didSet{
            // 赋值
            bgImageView.xd_setImage(imageWithURl: picUrl?.thumbnail_pic, placeHolderImageName: "timeline_image_placeholder")
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        //        backgroundColor = HMRandomColor()
        // 添加控件
        contentView.addSubview(bgImageView)
        // 添加约束
        bgImageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
    }
    
    // MARK: - 懒加载控件
    private lazy var bgImageView:UIImageView = {
        let view = UIImageView(imageViewName: "timeline_image_placeholder")
        // 图片显示样式
        view.contentMode = .scaleAspectFill
        view.layer.masksToBounds = true
        return view
    }()
}
























